package com.elitel.frame.base.service.impl;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import com.elitel.frame.business.dao.ext.DataBaseMetadataMapper;
import com.elitel.frame.main.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//	import com.elitel.common.redis.service.RedisCacheService;
import com.elitel.frame.base.component.RedisCacheProjectService;
import com.elitel.frame.base.component.RedisCacheTreeConfig;
import com.elitel.frame.base.component.RedisCatchBasicServer;
import com.elitel.frame.base.component.exportprojectdata.DataBaseConnInfo;
import com.elitel.frame.base.service.TreeConfigFileService;
import com.elitel.frame.business.dao.ext.ExecuteSqlMapper;
import com.elitel.frame.main.dao.CfgDbMapper;
import com.elitel.frame.main.dao.CfgExttreeMapper;
import com.elitel.frame.main.dao.CfgFieldMapper;
import com.elitel.frame.main.dao.CfgTableMapper;
import com.elitel.frame.main.dao.SysPrjserviceMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQueryfieldMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQuerysqlMapper;
import com.elitel.frame.main.dao.ext.ExtBaseTreeconfigMapper;
import com.elitel.frame.main.dao.ext.ExtCfgDbMapper;
import com.elitel.frame.main.dao.ext.ExtCfgExttreeMapper;
import com.elitel.frame.main.entity.ext.Census;
import com.elitel.frame.main.entity.ext.ExtBaseTreeconfig;
import com.elitel.frame.main.entity.ext.TreeConfig;
import com.elitel.frame.main.entity.ext.TreeConfig2;
import com.elitel.frame.main.entity.vo.PageResponseVo;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.sf.json.JSONObject;

@Service
public class TreeConfigFileServiceImpl implements TreeConfigFileService {

    @Resource
    private ExtBaseTreeconfigMapper extBaseTreeconfigMapper;


    @Resource
    private ExtCfgExttreeMapper extCfgExttreeMapper;

    @Resource
    private CfgDbMapper cfgDbMapper;

    @Resource
    private ExtCfgDbMapper extCfgDbMapper;

    @Resource
    private CfgExttreeMapper cfgExttreeMapper;

    @Resource
    private CfgTableMapper cfgTableMapper;

//		@Resource
//		private RedisCacheService redisCacheService;

    @Resource
    private RedisCatchBasicServer redisCatchBasicServer;

    @Resource
    private CfgFieldMapper cfgFieldMapper;

    @Resource
    private ExtBaseQuerysqlMapper extBaseQuerysqlMapper;

    @Resource
    private ExtBaseQueryfieldMapper extBaseQueryfieldMapper;

    @Resource
    private SysPrjserviceMapper sysPrjserviceMapper;

    @Autowired
    private RedisCacheProjectService redisCacheProjectService;

    @Resource
    private DataBaseConnInfo dataBaseConnInfo;

    @Resource
    private RedisCacheTreeConfig redisCacheTreeConfig;

    @Resource
    private ExecuteSqlMapper executeSqlMapper;

    //添加树节点
    @Override
    public String insertTreeNode(BaseTreeconfig baseTree) {
        String message = "fail";
        String type = dataBaseConnInfo.dataBaseType;
        int guid = 0;
        int ss = extBaseTreeconfigMapper.selectCount();
        if (ss > 0) {
            if ("mysql".equals(type) || type.equals("sqlite")) {
                guid = extBaseTreeconfigMapper.selectMaxGraMySql();
            } else if ("h2".equals(type)) {
                guid = extBaseTreeconfigMapper.selectMaxGraMySql();
            } else if ("oracle".equals(type)) {
                guid = extBaseTreeconfigMapper.selectMaxGra();
            } else if (DataSourceType.POSTGRES.equals(type)) {
                guid = extBaseTreeconfigMapper.selectMaxGraPG();
            }
        }
        baseTree.setGuid(String.valueOf(guid + 2));
        int a = extBaseTreeconfigMapper.insertSelective(baseTree);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public String updateTreeNode(BaseTreeconfig baseTreeconfig) {
        String message = "feil";
        int a = extBaseTreeconfigMapper.updateByPrimaryKeySelective(baseTreeconfig);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public String insertTreeList(CfgExttree cfgTreeExt) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(date);
        cfgTreeExt.setCreatedate(dateString);
        String message = "fail";
        int a = cfgExttreeMapper.insertSelective(cfgTreeExt);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public String deleteTreeList(String guid) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String updateTreeList(CfgExttree cfgTreeExt) {
        String message = "fail";
        int a = cfgExttreeMapper.updateByPrimaryKeySelective(cfgTreeExt);
        if (a > 0) {
            message = "success";
        }
        return message;
    }

    @Override
    public List<Census> getTreeList() {
        List<CfgDb> list = extCfgDbMapper.getAllListCfgDb();
        List<Census> censusList = new ArrayList<>();
        for (CfgDb c : list) {
            Census census = new Census();
            census.setDbMark(c.getDbMark());
            census.setDbSchema(c.getDbSchema());
            census.setDbVersion(c.getDbVersion());
            census.setDbIp(c.getDbIp());
            census.setPid("0");
            census.setId(c.getDbKey());
            census.setName(c.getDbMark());
            census.setDbName(c.getDbName());
            List<CfgExttree> treeList = extCfgExttreeMapper.getTreeList(c.getDbKey());
            if (treeList.size() > 0) {
                List<Census> list2 = new ArrayList<>();
                for (CfgExttree cs : treeList) {
                    Census census2 = new Census();
                    census2.setId(cs.getGuid());
                    census2.setPid(cs.getDtDbKey());
                    census2.setName(cs.getServicename());
                    list2.add(census2);
                }
                census.setChildren(list2);
            }
            censusList.add(census);
        }
        return censusList;
    }

    //		//获取
//		@Override
//		public List<BaseTreeconfig> selectTreeNode(String treeid, String sguid) {
//			String extend = extCfgExttreeMapper.selectTreeNode(treeid);
//			Map<String,Object> map = new HashMap<>();
//			map.put("treeid", treeid);
//			map.put("sguid", sguid);
//			List<BaseTreeconfig> list = null;
//			if (extend==null) {
//				list = extBaseTreeconfigMapper.selectTreeNode(map);
//			}else{
//
//			}
//			return list;
//		}
    @Override
    public List<BaseTreeconfig> selectTreeNode(String treeid, String sguid) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public CfgExttree selectTreeFile(String guid) {
        CfgExttree cfgExttree = cfgExttreeMapper.selectByPrimaryKey(guid);
        return cfgExttree;
    }

    @Override
    public int selectCountGUID(String guid) {
        int count = extCfgExttreeMapper.selectCountGUID(guid);
        return count;
    }

    @Override
    public List<ExtBaseTreeconfig> selectTreeShow(String guid, String treeid) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("treeid", treeid);
        List<BaseTreeconfig> list = extBaseTreeconfigMapper.selectTreeShow(map);
        List<BaseTreeconfig> listing = new ArrayList<>();
        Map<Integer, BaseTreeconfig> map2 = new TreeMap<Integer, BaseTreeconfig>();
        for (BaseTreeconfig b : list) {
            map2.put(b.getGrade(), b);
        }
        for (Map.Entry<Integer, BaseTreeconfig> entry : map2.entrySet()) {
            listing.add(entry.getValue());
        }
        List<ExtBaseTreeconfig> list2 = new ArrayList<>();
        for (BaseTreeconfig baseTreeconfig : listing) {
            ExtBaseTreeconfig extBaseTreeconfig = new ExtBaseTreeconfig();
            extBaseTreeconfig.setGuid(Integer.valueOf(baseTreeconfig.getGuid()));
            extBaseTreeconfig.setParentguid(Integer.parseInt(baseTreeconfig.getParentguid()));
            String xx = cfgTableMapper.selectTableNamees(baseTreeconfig.getDtConfigId());
//				if (xx!=null) {
//					extBaseTreeconfig.setDtConfigId(xx);
//				}else {
            extBaseTreeconfig.setDtConfigId(baseTreeconfig.getDtConfigId());
            //}
            extBaseTreeconfig.setFieldKey(baseTreeconfig.getFieldKey());
            extBaseTreeconfig.setFieldPKey(baseTreeconfig.getFieldPKey());
            extBaseTreeconfig.setFieldShow(baseTreeconfig.getFieldShow());
            extBaseTreeconfig.setGrade(baseTreeconfig.getGrade());
            extBaseTreeconfig.setQueryCon(baseTreeconfig.getQueryCon());
            extBaseTreeconfig.setServiceid(baseTreeconfig.getServiceid());
            extBaseTreeconfig.setTreename(baseTreeconfig.getTreename());
            list2.add(extBaseTreeconfig);
        }
        return list2;
    }

    @Override
    public BaseTreeconfig selectOneTree(String guid) {
        BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectOneTree(guid);
        return baseTreeconfig;
    }

    @Override
    public String deleteTreeNode(String guid, String treeid, String seid) {
        String message = "fail";
        Map<String, Object> map = new HashMap<>();
        map.put("treeid", treeid);
        map.put("seid", seid);
        try {
            BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectOneTree(guid);
            int maxA = extBaseTreeconfigMapper.selectMaxGrade(map);
            int a = extBaseTreeconfigMapper.deleteByPrimaryKey(guid);
            map.put("grades", a);
            int count = extBaseQueryfieldMapper.deleteQueryfield(map);
            int countsize = extBaseQuerysqlMapper.deleteQuerysql(map);
            List<Integer> list = new ArrayList<>();
            if (maxA == baseTreeconfig.getGrade()) {
                list.add(maxA);
            } else {
                for (int s = baseTreeconfig.getGrade(); s <= maxA; s++) {
                    list.add(s);
                }
                for (Integer integer : list) {
                    map.put("grades", integer);
                    if (a > 0) {
                        int ss = extBaseTreeconfigMapper.deleteCengJi(map);
                        count += extBaseQueryfieldMapper.deleteQueryfield(map);
                        countsize += extBaseQuerysqlMapper.deleteQuerysql(map);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public CfgExttree getOneCfgExttree(String guid) {
        CfgExttree cfgExttree = extCfgExttreeMapper.selectByPrimaryKey(guid);
        return cfgExttree;
    }

    @Override
    public BaseTreeconfig selectTreeConfig(String guid, String grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("grade", grade);
        BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectTreeConfig(map);
        return baseTreeconfig;
    }

    @Override
    public CfgTable selectTableName(String dtConfigId) {
        CfgTable cfgTable = cfgTableMapper.selectBtConfigId(dtConfigId);
        return cfgTable;
    }

    @Override
    public CfgDb selectCfgDb(String dtDbKey) {
        CfgDb cfgDb = cfgDbMapper.selectByPrimaryKey(dtDbKey);
        return cfgDb;
    }

    @Override
    public List<BaseTreeconfig> selectTreeConfigList(String guid) {
        List<BaseTreeconfig> list = extBaseTreeconfigMapper.selectTreeConfigList(guid);
        return list;
    }

    @Override
    public PageResponseVo<BaseTreeconfig> selectTreeConfigAll(String serviceid) {
        List<BaseTreeconfig> list = extBaseTreeconfigMapper.selectTreeConfigAll(serviceid);
        int count = extBaseTreeconfigMapper.selectAllCount(serviceid);
        PageResponseVo<BaseTreeconfig> pageResponseVo = new PageResponseVo<>();
        pageResponseVo.setRows(list);
        pageResponseVo.setTotal(count);
        return pageResponseVo;
    }

    @Override
    public CfgField getAllListCfgField(String configid, String dbKey) {
        Map<String, Object> map = new HashMap<>();
        map.put("configid", configid);
        map.put("dtname", dbKey);
        CfgField cfgField = cfgFieldMapper.selectColumnOne(map);
        return cfgField;
    }

    @Override
    public List<CfgDb> selectCfgDbList() {
        List<CfgDb> list = cfgDbMapper.selectAllDb();
        return list;
    }

    @Override
    public List<CfgTable> selectCfgTableAll() {
        List<CfgTable> list = cfgTableMapper.selectAllTable();
        return list;
    }

    @Override
    public List<CfgExttree> setTreeing() {
        List<CfgExttree> list = extCfgExttreeMapper.selectAllTree();
        return list;
    }

    @Override
    public String selectTableCN(String dtConfigId) {
        String xx = cfgTableMapper.selectTableNamees(dtConfigId);
        return xx;
    }

    @Override
    public List<CfgExttree> getTreeListaLL() {
        List<CfgExttree> list = extCfgExttreeMapper.selectAllTree();
        return list;
    }

    @Override
    public String deleteTreeConfig(String guid) {
        String message = "fail";
        int a = extCfgExttreeMapper.deleteByPrimaryKey(guid);
        if (a > 0) {
            extBaseQueryfieldMapper.deleteQueryfieldByServiceId(guid);
            extBaseQuerysqlMapper.deleteQuerysqlByServiceId(guid);
            message = "success";
        }
        return message;
    }

    @Override
    public Map<String, Object> selectColumnMap(String dbid) {
        List<CfgField> list = cfgFieldMapper.selectColumnList(dbid);
        Map<String, Object> map = new HashMap<>();
        for (CfgField c : list) {
            map.put(c.getDfName(), c.getDfNameCn());
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> executequerySql(String sqlString) {
        List<Map<String, Object>> list = extCfgExttreeMapper.executequerySql(sqlString);
        return list;
    }

    @Override
    public BaseTreeconfig selectTreeConfigOne(String guid, String grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("grade", grade);
        BaseTreeconfig baseTreeconfig = extBaseTreeconfigMapper.selectTreeConfigOne(map);
        return baseTreeconfig;
    }

    @Override
    public BaseQuerysql selectConQuery(String serviceID, String grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("serviceID", serviceID);
        map.put("grade", grade);
        BaseQuerysql baseQuerysql = extBaseQuerysqlMapper.selectByServerId(map);
        return baseQuerysql;
    }

    @Override
    public String getDBType(String serviceID) {
        CfgExttree cfgExttree = cfgExttreeMapper.selectByPrimaryKey(serviceID);
        CfgDb cfgDb = extCfgDbMapper.selectByPrimaryDBSign(cfgExttree.getDtDbKey());
        return cfgDb.getDbVersion();
    }

    @Override
    public List<BaseQueryfield> selectTreeColumn(String guid) {
        List<BaseQueryfield> list = extBaseQueryfieldMapper.selectQueryFiled(guid);
        return list;
    }

    @Override
    public void deletetreeconfigServerByPrjservice(SysPrjservice prjservice) {
        //删除服务中间表信息
        sysPrjserviceMapper.deleteByPrimaryKey(prjservice.getGuid());
        if (extCfgExttreeMapper.selectByPrimaryKey(prjservice.getServicecode()) != null) {
            extCfgExttreeMapper.deleteByPrimaryKey(prjservice.getServicecode());
        }
        extBaseQueryfieldMapper.deleteQueryfieldByServiceId(prjservice.getServicecode());
        if (extBaseQuerysqlMapper.selectByServiceId(prjservice.getServicecode()) > 1) {
            extBaseQuerysqlMapper.deleteQuerysqlByServiceId(prjservice.getServicecode());
        }
        extBaseTreeconfigMapper.deleteByServiceId(prjservice.getServicecode());
        //刷新工程服务树
        redisCacheProjectService.freshProjectServerTree();
    }

    public BaseQuerysql selectQuerySql(String guid, int grade) {
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("grade", grade);
        BaseQuerysql baseQuerysql = extBaseQuerysqlMapper.selectQuerySql(map);
        //BaseQuerysql baseQuerysql = null;
        return baseQuerysql;
    }

    /**
     * <pre>processSqlByFreemarker(freemarker处理sql)
     * @author：FanWenquan
     * @date：2017年8月31日 上午10:34:17
     * @param sql
     * @param root
     * @return</pre>
     */
    private String processSqlByFreemarker(String sql, Map root) {
        String str = "";
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", sql);
        cfg.setTemplateLoader(stringLoader);
        try {
            Template template = cfg.getTemplate("myTemplate", "utf-8");
            StringWriter writer = new StringWriter();
            template.process(root, writer);
            str = writer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return str;
    }

    public List<TreeConfig> recursiveTree(String pid, List<BaseTreeconfig> btcList, int grade, String tableName, String querycon) {
        TreeConfig node = new TreeConfig();
        BaseTreeconfig baseTree = null;
        for (BaseTreeconfig baseTreeconfig : btcList) {
            if (grade == baseTreeconfig.getGrade()) {
                baseTree = baseTreeconfig;
                break;
            }
        }
        if (baseTree == null) {
            return null;
        }
        CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTree.getDtConfigId());
        String sql = "SELECT " + baseTree.getFieldKey() + " " + "AS ID," + " " + baseTree.getFieldShow() + " " + "AS NAME," + "'" + pid + "'" + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE  " + baseTree.getFieldPKey() + " = '" + pid + "'" + querycon;
        List<Map<String, Object>> lists = executeSqlMapper.executequerySql(sql);
        List<TreeConfig> list = new ArrayList<>();
        for (Map<String, Object> map : lists) {
            TreeConfig treeConfig = new TreeConfig();
            treeConfig.setId((String) map.get("ID"));
            treeConfig.setName((String) map.get("NAME"));
            treeConfig.setPid(pid);
            treeConfig.setGrade(grade);
            list.add(treeConfig);
        }
        for (TreeConfig treeConfig : list) {
            List<TreeConfig> n = recursiveTree(treeConfig.getId(), btcList, grade + 1, tableName, querycon); //递归
            treeConfig.setChildren(n);
        }
        return list;
    }

    @Override
    public Object selectTreeConfigFile(CfgDb cfgDb, String guid, String conquery) {
        Map mapsts = new HashMap();
        if (conquery != null && !"".equals(conquery)) {
            JSONObject jasonObject = JSONObject.fromObject(conquery);
            mapsts = (Map) jasonObject;
        }
        CfgExttree cfgExttree = extCfgExttreeMapper.selectByPrimaryKey(guid);
        List<TreeConfig> list = new ArrayList<>();
        if (Integer.parseInt(String.valueOf(cfgExttree.getIslazyload())) == 1) {
            BaseQuerysql baseQuerysql = selectQuerySql(guid, 1);
            String sqlconquery = "";
            if (baseQuerysql != null) {
                sqlconquery = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
            }
            if (cfgExttree.getIsusetop() == 0) {
                System.out.println("慢加载xx不用顶级节点");
                BaseTreeconfig baseTreeconfig = redisCacheTreeConfig.getBaseTreeCacheOne(guid, 1);
                CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
                // sqlString = "SELECT "+baseTreeconfig.getFieldKey()+" "+"AS ID,"+" "+baseTreeconfig.getFieldShow()+" "+"AS NAME,"+" "+0+" "+"AS PID FROM "+cfgTable.getDtName();
                //sqlString = "SELECT "+baseTreeconfig.getFieldKey()+" "+"AS ID,"+" "+baseTreeconfig.getFieldShow()+" "+"AS NAME,"+" "+0+" "+"AS PID FROM "+cfgTable.getDtName()+" "+"WHERE 1=1"+" "+baseTreeconfig.getQueryCon();
                String sqlString = "SELECT * FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + " " + sqlconquery;
                List<Map<String, Object>> list2 = executeSqlMapper.executequerySql(sqlString);
                List<Map<String, Object>> list3 = new ArrayList<>();
                for (Map<String, Object> m : list2) {
                    Map<String, Object> map = new HashMap<>();
                    //System.out.println(m.toString());
                    Map<String, Object> map6 = new HashMap<>();
                    for (Map.Entry<String, Object> entry : m.entrySet()) {
                        if (entry.getValue() != null) {
                            //System.out.println(entry.toString());
                            if (baseTreeconfig.getFieldKey().equals(entry.getKey())) {
                                map.put("id", entry.getValue());
                            }
                            if (baseTreeconfig.getFieldShow().equals(entry.getKey())) {
                                map.put("name", entry.getValue());
                            }
                        }
                    }

//						for(Map.Entry<String, Object> entry:map6.entrySet()){
//							map.put(entry.getKey(), entry.getValue());
//						}
                    map.put("pid", "1");
                    map.put("otherfield", m);
                    list3.add(map);
                }
                return list3;
            } else {
                System.out.println("慢加载用顶级节点");
                List<TreeConfig> configs = new ArrayList<>();
                TreeConfig2 treeCon = new TreeConfig2();
                treeCon.setId("1");
                treeCon.setName(cfgExttree.getTopnode());
                treeCon.setPid("0");
                //list.add(treeCon);
                BaseTreeconfig baseTreeconfig = redisCacheTreeConfig.getBaseTreeCacheOne(guid, 1);
                CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(baseTreeconfig.getDtConfigId());
                String sqlString = "SELECT * FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + " " + sqlconquery;
                List<Map<String, Object>> list2 = executeSqlMapper.executequerySql(sqlString);
                List<Map<String, Object>> list3 = new ArrayList<>();
                for (Map<String, Object> m : list2) {
                    Map<String, Object> map = new HashMap<>();
                    for (Map.Entry<String, Object> entry : m.entrySet()) {
                        if (baseTreeconfig.getFieldKey().equals(entry.getKey())) {
                            map.put("id", entry.getValue());
                        }
                        if (baseTreeconfig.getFieldShow().equals(entry.getKey())) {
                            map.put("name", entry.getValue());
                        }
                        map.put("otherfield", m);
                    }
                    map.put("pid", "1");
                    list3.add(map);
                }
                treeCon.setChildren(list3);
                return treeCon;
            }
        } else {
            if (cfgExttree.getIsusetop() == 0) {
                System.out.println("全加载用顶级节点");
                TreeConfig treeCon = new TreeConfig();
                treeCon.setId("1");
                treeCon.setName(cfgExttree.getTopnode());
                treeCon.setPid("0");
                list.add(treeCon);
                List<BaseTreeconfig> baseTreeconfigLists = redisCacheTreeConfig.getBaseTreeCache(guid);
                TreeMap<Integer, BaseTreeconfig> treeMaping = new TreeMap<Integer, BaseTreeconfig>();
                for (BaseTreeconfig bs : baseTreeconfigLists) {
                    treeMaping.put(bs.getGrade(), bs);
                }
                List<BaseTreeconfig> baseTreeconfigList = new ArrayList<>();
                for (Map.Entry<Integer, BaseTreeconfig> entry : treeMaping.entrySet()) {
                    baseTreeconfigList.add(entry.getValue());
                }
                Map<String, Object> map = new HashMap<>();
                List<TreeConfig> tList = new ArrayList<>();
                String sql = "";
                int a = 1;
                Map<String, List<TreeConfig>> conMap = new HashMap<>();
                List<TreeConfig> lConfigs = new ArrayList<>();
                for (BaseTreeconfig b : baseTreeconfigList) {
                    CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(b.getDtConfigId());
                    if (b.getGrade() == 1) {
                        BaseQuerysql baseQuerysql = selectQuerySql(guid, 1);
                        String sqlconquerys = "";
                        if (baseQuerysql != null) {
                            sqlconquerys = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
                        }
                        sql = "SELECT " + b.getFieldKey() + " " + "AS ID," + " " + b.getFieldShow() + " " + "AS NAME," + " " + 0 + " " + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + sqlconquerys;
                        List<Map<String, Object>> lists = executeSqlMapper.executequerySql(sql);
                        List<String> conList = new ArrayList<>();
                        for (Map<String, Object> mp : lists) {
                            TreeConfig treeConfig = new TreeConfig();
                            conList.add((String) mp.get("ID"));
                            treeConfig.setId((String) mp.get("ID"));
                            treeConfig.setName((String) mp.get("NAME"));
                            treeConfig.setPid("1");
                            treeConfig.setGrade(1);
                            tList.add(treeConfig);
                            lConfigs.add(treeConfig);
                        }
                        int grade = 2;
                        if (lConfigs.size() > 0) {
                            for (TreeConfig treeConfig : lConfigs) {
                                BaseQuerysql baseQuerysqles = selectQuerySql(guid, grade);
                                if (baseQuerysqles != null) {
                                    sqlconquerys = processSqlByFreemarker(baseQuerysqles.getSqlcontent(), mapsts);
                                }
                                List<TreeConfig> n = recursiveTree(treeConfig.getId(), baseTreeconfigLists, grade, cfgTable.getDtName(), sqlconquerys); //递归
                                treeConfig.setChildren(n);
                                //grade++;
                            }
                        }
                    }
                }
                treeCon.setChildren(lConfigs);
                return lConfigs;
            } else {
                System.out.println("全加载用顶级节点");
                TreeConfig treeCon = new TreeConfig();
                treeCon.setId("1");
                treeCon.setName(cfgExttree.getTopnode());
                treeCon.setPid("0");
                list.add(treeCon);
                List<BaseTreeconfig> baseTreeconfigLists = redisCacheTreeConfig.getBaseTreeCache(guid);
                TreeMap<Integer, BaseTreeconfig> treeMaping = new TreeMap<Integer, BaseTreeconfig>();
                for (BaseTreeconfig bs : baseTreeconfigLists) {
                    treeMaping.put(bs.getGrade(), bs);
                }
                List<BaseTreeconfig> baseTreeconfigList = new ArrayList<>();
                for (Map.Entry<Integer, BaseTreeconfig> entry : treeMaping.entrySet()) {
                    baseTreeconfigList.add(entry.getValue());
                }
                Map<String, Object> map = new HashMap<>();
                List<TreeConfig> tList = new ArrayList<>();
                String sql = "";
                int a = 1;
                Map<String, List<TreeConfig>> conMap = new HashMap<>();
                List<TreeConfig> lConfigs = new ArrayList<>();
                for (BaseTreeconfig b : baseTreeconfigList) {
                    CfgTable cfgTable = redisCacheTreeConfig.selectCfgTableOne(b.getDtConfigId());
                    if (b.getGrade() == 1) {
                        BaseQuerysql baseQuerysql = selectQuerySql(guid, 1);
                        String sqlconquerys = "";
                        if (baseQuerysql != null) {
                            sqlconquerys = processSqlByFreemarker(baseQuerysql.getSqlcontent(), mapsts);
                        }
                        sql = "SELECT " + b.getFieldKey() + " " + "AS ID," + " " + b.getFieldShow() + " " + "AS NAME," + " " + 0 + " " + "AS PID FROM " + cfgTable.getDtName() + " " + "WHERE 1=1" + sqlconquerys;
                        List<Map<String, Object>> lists = executeSqlMapper.executequerySql(sql);
                        List<String> conList = new ArrayList<>();
                        for (Map<String, Object> mp : lists) {
                            TreeConfig treeConfig = new TreeConfig();
                            conList.add((String) mp.get("ID"));
                            treeConfig.setId((String) mp.get("ID"));
                            treeConfig.setName((String) mp.get("NAME"));
                            treeConfig.setPid("1");
                            treeConfig.setGrade(1);
                            tList.add(treeConfig);
                            lConfigs.add(treeConfig);
                        }
                        int grade = 2;
                        if (lConfigs.size() > 0) {
                            for (TreeConfig treeConfig : lConfigs) {
                                BaseQuerysql baseQuerysqles = selectQuerySql(guid, grade);
                                if (baseQuerysqles != null) {
                                    sqlconquerys = processSqlByFreemarker(baseQuerysqles.getSqlcontent(), mapsts);
                                }
                                List<TreeConfig> n = recursiveTree(treeConfig.getId(), baseTreeconfigLists, grade, cfgTable.getDtName(), sqlconquerys); //递归
                                treeConfig.setChildren(n);
                                //grade++;
                            }
                        }
                    }
                }
                treeCon.setChildren(lConfigs);
                return treeCon;
            }
        }
    }


}

